﻿using System;
using System.Collections.Generic;
using System.Threading;

namespace CommandLib
{
    /*
     * 用法：
      BackTaskListRun.AddFunc(delegate
                {
                    Console.WriteLine("run:"+i);
                },null);
     */
    /// <summary>
    /// 后台执行队列
    /// </summary>
    public class BackTaskListRun
    {
        private static Thread th = null;

        private class TaskEntity
        {
            public TaskEntity(Action<object> func, object data)
            {
                this.Function = func;
                this.Data = data;
            }

            public Action<object> Function;
            public object Data;
        }

        static Queue<TaskEntity> list = new Queue<TaskEntity>();
        static BackTaskListRun()
        {
            if (th == null)
            {
                th = new Thread(RunTask);
                th.IsBackground = true;
            }
            if (th.ThreadState != ThreadState.Running)
            {
                th.Start();

            }

        }

        static void RunTask()
        {
            while (true)
            {
                if (list.Count == 0)
                {
                    Thread.Sleep(1000);
                }
                else
                {
                    TaskEntity entity;
                    lock (list)
                    {
                        entity = list.Dequeue();
                    }
                    try
                    {
                        entity.Function(entity.Data);
                    }
                    catch (Exception e)
                    {

                       
                    }

                }

            }
        }
        /// <summary>
        /// 添加质行队列方法
        /// </summary>
        /// <param name="func"></param>
        /// <param name="data"></param>
        public static void AddFunc(Action<object> func, object data)
        {
            list.Enqueue(new TaskEntity(func, data));
        }
    }
}
